const app = getApp()
// 要删除的房屋的id和房屋在数组中的下标
let house_id = 0
let house_index = 0
Page({
  data: {
    houseList: [], // 房屋数组
    dialogVisible: false,
  },

  onShow() {
    this.getHouseList()
  },

  // 1. 获取房屋列表
  async getHouseList() {
    const { code, data: houseList } = await wx.http.get('/room')
    if (code !== 10000) return wx.utils.toast()
    this.setData({
      houseList,
    })
  },

  swipeClose(ev) {
    const { position, instance } = ev.detail
    if (position === 'right') {
      // 显示 Dialog 对话框
      this.setData({
        dialogVisible: true,
      })

      // console.log(ev.mark)
      // 记录要删除对象的数据
      house_id = ev.mark.id
      house_index = ev.mark.index

      // swiper-cell 滑块关闭
      instance.close()
    }
  },

  addHouse() {
    wx.navigateTo({
      url: '/house_pkg/pages/locate/index',
    })
  },

  // 1. 关闭对话框
  dialogClose(ev) {
    // console.log(ev)
    // if(ev.detail === 'confirm'){
    //   this.deleteHouse()
    // }
    ev.detail === 'confirm' && this.deleteHouse()
  },

  // 2. 删除房屋
  async deleteHouse() {
    // 2.1 调用接口
    const { code } = await wx.http.delete(`/room/${house_id}`)
    if (code !== 10000) return wx.utils.toast('删除房屋失败')
    // 2.2 更新数据
    this.data.houseList.splice(house_index, 1)
    this.setData({
      houseList: this.data.houseList,
    })
  },

  // 3. 去房屋详情
  goDetail(ev) {
    wx.navigateTo({
      url: '/house_pkg/pages/detail/index?id=' + ev.mark.id,
    })
  },
})
